<template>
	<view class="page-background">
		<uni-nav-bar :border="false" statusBar fixed="true" :title="title" @clickLeft="clickBack">
			<!-- <template>标题栏</template> -->
			<template v-slot:left>
				<uni-icons type="back" size="26" />
			</template>
			<!-- <template v-slot:right>
				<text v-show="isShowEdit" style="font-size: 34rpx;">编辑</text>
			</template> -->
		</uni-nav-bar>
		<view class="uni-container">
			<uni-forms ref="form" :model="formData" label-position="top" validate-trigger="submit"
				err-show-type="toast">
				<uni-forms-item name="fault_description" label="故障描述" required>
					<uni-easyinput placeholder="对设备故障的简要描述" v-model="formData.fault_description"
						trim="both"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="fault_code" label="故障代码">
					<uni-easyinput placeholder="诊断系统显示的故障代码" v-model="formData.fault_code" trim="both"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="brand" label="品牌">
					<uni-easyinput placeholder="设备品牌" v-model="formData.brand"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="model" label="型号">
					<uni-easyinput placeholder="设备型号" v-model="formData.model"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="fault_information" label="详细信息" required>
					<uni-easyinput placeholder="故障详细信息及最终解决方案，最多输入200个字符。" :maxlength=200
						v-model="formData.fault_information" trim="both" type="textarea" auto-height></uni-easyinput>
				</uni-forms-item>

				<uni-forms-item name="private" label="私有">
					<view class="switch-align">
						<switch :checked=formData.private @change="privateChange" />
					</view>
				</uni-forms-item>

				<uni-forms-item name="fault_photo" label="故障照片">
					<uni-file-picker file-mediatype="image" file-extname="jpg,png" :limit="10" return-type="array"
						:image-styles="imagestyles" v-model="formData.fault_photo"></uni-file-picker>
				</uni-forms-item>
				<view class="button-group">
					<view class="submit-button-lg button-normal" hover-class="button-hover" @click="submit">提交
					</view>
				</view>
			</uni-forms>
		</view>
	</view>
</template>

<script>
	import { validator } from '../../js_sdk/validator/kfault-sample-set.js';
	// 关闭系统自带的加载动画
	const faultSample = uniCloud.importObject("star-service", {
		customUI: true // 取消自动展示的交互提示界面
	})

	// const db = uniCloud.database();
	// const dbCollectionName = 'kfault-sample-set';


	function getValidator(fields) {
		// console.log(fields);
		let result = {}
		for (let key in validator) {
			if (fields.indexOf(key) > -1) {
				result[key] = validator[key]
			}
		}
		// console.log(result);
		return result
	}

	export default {
		data() {
			let formData = {
				"_id": "",
				"fault_description": "",
				"fault_code": "",
				"brand": "",
				"model": "",
				"fault_information": "",
				"fault_photo": [],
				"is_delete": false,
				"is_lock": false,
				"private": false,
				"sort": null,
				"user_id": "",
			}
			return {
				title: "",
				formData,
				formOptions: {},
				brands: [],
				models: [],
				iStatusBarHeight: 0,
				rules: {
					...getValidator(Object.keys(formData))
				},

				imagestyles: {
					border: { // 如果为 Boolean 值，可以控制边框显示与否
						radius: "10%", // 边框圆角，支持百分比
					}
				}
			}
		},
		onLoad(param) {
			// 如果是编辑从全局变了获取单条记录数据
			if (param.Action === "edit") {
				this.title = "编辑"
				// console.log(data)
				this.formData = JSON.parse(uni.getStorageSync('sampleItem'))
			} else if (param.Action === "add") {
				this.title = "新增"
				this.formData = {}
			}
		},

		onReady() {
			this.$refs.form.setRules(this.rules)
		},

		computed: {
			// BrandsList() {
			// 	let brands = []
			// 	for (let i = 0; i < this.brands.length; i++) {
			// 		brands[i] = this.brands[i].brand
			// 	}
			// 	console.log(brands);
			// 	return brands
			// },
			// BrandsDataList() {
			// 	let brands = []
			// 	for (let i = 0; i < this.brands.length; i++) {
			// 		let brand = {}
			// 		brand.value = this.brands[i]._id
			// 		brand.text = this.brands[i].brand
			// 		brands.push(brand)
			// 	}
			// 	console.log(brands);
			// 	return brands
			// }
		},

		methods: {
			// 返回按钮事件
			clickBack() {
				uni.navigateBack()
			},

			/**
			 * 获取品牌列表
			 */
			getBronds() {
				faultSample.getBrands().then(res => {
					// console.log(res.data)
					this.brands = res.data
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},

			brandschange() {


			},

			// 是否私有修改
			privateChange(e) {
				this.$set(this.formData, 'private', e.detail.value)
			},

			/**
			 * 验证表单并提交
			 */
			async submit() {
				uni.showLoading({
					mask: true
				})

				this.$refs.form.validate().then(res => {
					if (this.title === "新增") {
						faultSample.addFaultSample(res).then(addres => {
							if (addres.errCode === 0) {
								uni.showToast({
									icon: 'none',
									title: '新增成功'
								})
								this.getOpenerEventChannel().emit('refreshData')
								setTimeout(() => uni.navigateBack(), 500)
							}
						})
					} else if (this.title === "编辑") {
						// console.log(res)
						faultSample.updataFaultSample(this.formData._id, res).then(editres => {
							if (editres.errCode === 0) {
								uni.showToast({
									icon: 'none',
									title: '编辑成功'
								})
								uni.setStorageSync('sampleItem', JSON.stringify(res))
								console.log(JSON.parse(uni.getStorageSync('sampleItem')))
								// this.getOpenerEventChannel().emit('refreshData')
								// setTimeout(() => uni.navigateBack(), 500)
							}

						})
					}
				}).catch(err => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			addSubmitForm(value) {
				// 使用 clientDB 提交数据
				faultSample.addFaultSample(value).then(res => {
					if (res.errCode == 0) {
						uni.showToast({
							icon: 'none',
							title: '新增成功'
						})
					}
				}).catch(err => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})

			}
		}
	}
</script>

<style lang="scss">
	@import "../../uni.scss";

	.uni-status-bar {
		background-color: $uni-bg-color;
		// height: 20px;
	}

	.uni-container {
		// margin: 10rpx; //列表上下间距
		border-radius: 20rpx; //圆角直径
		background: $uni-bg-color; //列表容器背景色
		padding: 10px;

		margin-top: 8px;
		margin-left: 10px;
		margin-right: 10px;
		margin-bottom: 8px;
	}

	.button-group {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center; //居中对齐
		margin-top: 100rpx; //距离上部组件距离
	}

	.switch-align {
		display: flex; //子元素对齐方式，弹性盒子
		justify-content: flex-end; //子元素靠左对齐
		margin-top: 5rpx;
	}
</style>